import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;

/**
 *
 * @author Seth Yost
 */
public class Buddy_gui extends javax.swing.JFrame {
	private Socket connection;
	private PrintWriter writer;
	private ListenerThread listener = null;
	private BufferedReader reader;
	private HashMap<String, Chat_gui> chatList;

	/**
	 * Creates new form Buddy_gui
	 */
	public Buddy_gui(Socket s, BufferedReader r, PrintWriter w) {
		initComponents();
		writer = w;
		connection = s;
		reader = r;
		chatList = new HashMap<String, Chat_gui>();
	}
	
	public void startListener()
	{
		if (listener == null)
		{
			listener = new ListenerThread(this, reader);
			listener.start();
		}
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jScrollPane1 = new JScrollPane();
		AllContactsModel = new DefaultListModel<String>();
		AllContacts = new JList<String>(AllContactsModel);
		jLabel1 = new JLabel();
		jScrollPane2 = new JScrollPane();
		BuddiesModel = new DefaultListModel<String>();
		Buddies = new JList<String>(BuddiesModel);
		jLabel2 = new JLabel();
		Chat = new JButton();
		AddToBuddies = new JButton();
		GroupChat = new JButton();
		RemoveBuddy = new JButton();
		
		this.addWindowListener(new java.awt.event.WindowAdapter() {
			@Override
			public void windowClosing(java.awt.event.WindowEvent e) {
				writer.write("2 " + getTitle());
				writer.flush();
				System.exit(0);
			}
		});

		jScrollPane1.setViewportView(AllContacts);

		jLabel1.setText("All Users:");

		jScrollPane2.setViewportView(Buddies);

		jLabel2.setText("Buddies:");

		Chat.setText("Chat");
		Chat.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				ChatMouseActionPerformed(evt);
			}
		});

		AddToBuddies.setText("Add to Buddies");
		AddToBuddies.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				AddToBuddiesActionPerformed(evt);
			}
		});
		
		RemoveBuddy.setText("Remove Buddy");
		RemoveBuddy.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				RemoveBuddyActionPerformed(evt);
			}
		});

		GroupChat.setText("Group Chat");
		GroupChat.setVisible(false);
		GroupChat.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				GroupChatMouseClicked(evt);
			}
		});

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(
			layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(layout.createSequentialGroup()
				.addContainerGap()
				.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
					.addComponent(jScrollPane1)
					.addComponent(jScrollPane2)
					.addComponent(jLabel1)
					.addComponent(jLabel2)
					.addComponent(AddToBuddies, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
						.addComponent(RemoveBuddy)
						.addComponent(GroupChat)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(Chat)))
				.addContainerGap())
		);
		layout.setVerticalGroup(
			layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
			.addGroup(layout.createSequentialGroup()
				.addContainerGap()
				.addComponent(jLabel1)
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE)
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(AddToBuddies)
				.addGap(18, 18, 18)
				.addComponent(jLabel2)
				.addGap(3, 3, 3)
				.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
				.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
					.addComponent(RemoveBuddy)
					.addComponent(Chat)
					.addComponent(GroupChat))
				.addContainerGap())
		);
		pack();
	}// </editor-fold>
	
	public void addToBuddyList(String b)
	{
		BuddiesModel.addElement(b);
	}
	
	public void addToOnlineList(String u)
	{
		AllContactsModel.addElement(u);
	}
	
	public void removeFromOnlineList(String b)
	{
		for (int i = 0; i < AllContactsModel.size(); i++)
		{
			if (AllContactsModel.get(i).equals(b))
			{
				AllContactsModel.remove(i);
				return;
			}
		}
	}
	
	public void removeFromBuddyList(String b)
	{
		for (int i = 0; i < BuddiesModel.size(); i++)
		{
			if (BuddiesModel.get(i).equals(b))
			{
				BuddiesModel.remove(i);
				return;
			}
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected void RemoveBuddyActionPerformed(ActionEvent evt) {
		try
		{
			String b = Buddies.getSelectedValue().toString();
			if (b != null)
			{
				writer.write("9 " + getTitle() + " " + b + "\n");
				writer.flush();
				removeFromBuddyList(b);
			}
		} catch (NullPointerException e) {}
	}

	private void ChatMouseActionPerformed(ActionEvent evt) {
		try {
			String user = Buddies.getSelectedValue().toString();
			Chat_gui chat = new Chat_gui(user, this);
			chat.setVisible(true);
			chatList.put(user, chat);
		} catch (NullPointerException e) {}
	}

	private void AddToBuddiesActionPerformed(java.awt.event.ActionEvent evt) {
		String u = null;
		try
		{
			u = AllContacts.getSelectedValue().toString();
		}
		catch (NullPointerException e)
		{
			u = (String) JOptionPane.showInputDialog(this, "Buddy name:");
		}
		
		if (u != null)
		{
			removeFromOnlineList(u);
			writer.write("8 " + getTitle() + " " + u + "\n");
			writer.flush();
		}
	}

	@SuppressWarnings("rawtypes")
	private void GroupChatMouseClicked(java.awt.event.MouseEvent evt) {
		String user = Buddies.getSelectedValue().toString();
		Chat_gui chat = new Chat_gui(user, this);
		chat.setTitle(user);
		chat.setVisible(true);
		//chatList.add(chat);
	}
	
	//finds the correct chat gui and passes it the message
	protected void incomingMessage(String mess)
	{
		String[] message = mess.split(" ");
		
		if (message.length < 3)
			return;
		
		Chat_gui chat = chatList.get(message[0]);
		
		if (chat == null)
		{
			chat = new Chat_gui(message[0], this);
			chat.setVisible(true);
			chatList.put(message[0], chat);
		}
		
		// fake a server message if required
		if (message[1].equals("UNDELIVERABLE"))
		{
			message = new String[]{"Server", "", "Message could not be delivered!"};
		}
		
		String msg = "";
		for (int i = 2; i < message.length; i++)
		{
			msg += message[i] + " ";
		}
		
		chat.message(message[0], msg);
	}
	
	protected void send(String to, String msg)
	{
		String out = "3 " + getTitle() + " " + to + " " + msg + "\n";
		writer.write(out);
		writer.flush();
	}
	
	protected void unregisterChatWindow(String buddy)
	{
		chatList.remove(buddy);
	}
	
	protected void setTyping(String user)
	{
		writer.write("10 " + getTitle() + " " + user + "\n");
		writer.flush();
	}
	
	protected void setEnteredText(String user)
	{
		writer.write("11 " + getTitle() + " " + user + "\n");
		writer.flush();
	}
	
	protected void incomingTyping(String user)
	{
		Chat_gui chat = chatList.get(user);
		if (chat != null)
		{
			chat.setStatus(user + " is typing...");
		}
	}
	
	protected void incomingEnteredText(String user)
	{
		Chat_gui chat = chatList.get(user);
		chat.setStatus(user + " has entered text.");
	}
	
	// Variables declaration - do not modify
	private javax.swing.JButton AddToBuddies;
	private javax.swing.JList<String> AllContacts;
	private DefaultListModel<String> AllContactsModel;
	private javax.swing.JList<String> Buddies;
	private DefaultListModel<String> BuddiesModel;
	private javax.swing.JButton Chat;
	private javax.swing.JButton GroupChat;
	private javax.swing.JButton RemoveBuddy;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane2;
	// End of variables declaration
}
